package com.exercises;

import java.util.HashMap;
import java.util.Map;

class Exercise930 {
    public static void main(String[] args) {
        numSubarraysWithSum(new int[]{1, 0, 1, 0, 1}, 2);
    }

    public static int numSubarraysWithSum(int[] nums, int goal) {
        //假设子数组为 i到j 则sumJ-sumI=goal
        int sumJ = 0;
        int length = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        int result = 0;
        for (int i = 0; i < length; i++) {
            //i-1之前的前缀和出现次数
            map.put(sumJ, map.getOrDefault(sumJ, 0) + 1);
            sumJ += nums[i];
            result += map.getOrDefault(sumJ - goal, 0);
            System.out.println(nums[i] + ":" + result);
        }
        return result;
    }


}
